package tech.moya.flexbase.core
{
	import flash.data.SQLConnection;
	import flash.filesystem.File;
	
	import mx.containers.Panel;
	
	public class BaseContext
	{
		private var connection:SQLConnection = null;
		private var dbFile:File = null;
		private static var contextArray:Array = new Array();
		private static var queryAreaArray:Array = new Array();
		private static var currentQueryContextName:String;
		
		public function BaseContext(dbFile:String)
		{
			
			this.dbFile = new File(dbFile);
			connection = new SQLConnection();
		}
		
		public static function getFileContext(dbFile:String):BaseContext{
			
			if(contextArray[dbFile] != null){
				return BaseContext(contextArray[dbFile]);
			}else{
				var context = new BaseContext(dbFile);
				contextArray[dbFile] = context;
				return context;
			}
			
		}
		
		public function openConnection():SQLConnection{
			if(connection.connected)
				throw new Error("Connection is opened");
			connection.open(dbFile);
			return connection;
		}
		
		public function closeConnection(connection:SQLConnection){
			connection.close();
		}
		
		public static function getQueryPanelContext(queryPanel:Panel,dbFile:String=null):BaseContext{
			var pnl = queryAreaArray[queryPanel.name];
			if(pnl == null && dbFile == null){
				return null;
			}
			else if(pnl == null){
				queryAreaArray[queryPanel.name] = new BaseContext(dbFile);
			}
			currentQueryContextName = queryPanel.name;
			return BaseContext(queryAreaArray[queryPanel.name]); 
		}
		
		public static function getCurrentQueryPanelCnxt():BaseContext{
			if(currentQueryContextName != null)
				return queryAreaArray[currentQueryContextName];
			return null;
		}
		

	}
}